package com.student.wym.controller;

import com.student.wym.po.Teacher;
import com.student.wym.service.ITeacherService;
import com.student.wym.util.JSONResult;
import com.student.wym.util.PageList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/teacher")
public class TeacherController {

    @Autowired
    private ITeacherService teacherService;

    @RequestMapping(value = "/goPage", method = RequestMethod.GET)
    public String goPage() {
        return "list_teacher";
    }

    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @ResponseBody
    public PageList list() {
        List<Teacher> teachers = teacherService.getAll();
        PageList resultList = new PageList();
        resultList.setRows(teachers);
        resultList.setTotal(teachers.size());
        return resultList;
    }

    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult delete(int id) {
        try {
            teacherService.delete(id);
            return new JSONResult(0);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return new JSONResult(1, "删除出现错误");
        }
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody //po->vo
    public JSONResult save(Teacher teacher) {
        /**
         * 新增
         */
        if (teacher.getId() == null) {
            teacher.setCreateTime(new Date());
            teacher.setState(0);
            try {
                teacherService.save(teacher);
                return new JSONResult(0);
            } catch (Exception e) {
                System.out.println(e.getMessage());
                return new JSONResult(1, "保存出现错误");
            }
        } else {
            try {
                teacherService.update(teacher);
                return new JSONResult(0);
            } catch (Exception e) {
                System.out.println(e.getMessage());
                return new JSONResult(1, "修改出现错误");
            }
        }
    }


}
